// Copyright 2007-2010 Comdiv (F. Sadykov) - http://code.google.com/u/fagim.sadykov/
// Supported by Media Technology LTD 
//  
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//  
//      http://www.apache.org/licenses/LICENSE-2.0
//  
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 
// MODIFICATIONS HAVE BEEN MADE TO THIS FILE
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Comdiv.Extensions;
using Comdiv.Logging;

namespace Comdiv.Doc{
    public class LoadAssembliesStep : DocumentProcessorStep<LoadAssembliesStep>{
        public IEnumerable<AssemblyDescriptor> GetAssemblyDescriptors(){
            var dir = MyQuery.InputDirectory.mapPath();
            foreach (var name in Directory.GetFiles(dir, "*.dll")){
                var fname = Path.GetFileNameWithoutExtension(name);
                if (MyQuery.ExcludePatterns.yes() &&
                    null != MyQuery.ExcludePatterns.FirstOrDefault(x => Regex.IsMatch(fname, x))){
                    continue;
                }

                if (MyQuery.IncludePatterns.yes() &&
                    null == MyQuery.IncludePatterns.FirstOrDefault(x => Regex.IsMatch(fname, x))){
                    continue;
                }

                var result = new AssemblyDescriptor();
                result.Assembly = Assembly.LoadFrom(name);

                var xdoc = Path.Combine(dir, fname + ".xml");
                if (File.Exists(xdoc)){
                    result.Documentation = XElement.Load(xdoc);
                }
                else{
                    result.Documentation = new XElement("doc");
                }

                yield return result;
            }
        }

        private ILog log = logger.get<LoadAssembliesStep>();

        protected override void internalProcess(DocumentQuery query){
            MyQuery = query;
            foreach (var ad in GetAssemblyDescriptors()){
                log.Info("assembly: "+ad.Assembly.GetName().Name);
                MyQuery.Libs.Add(ad);
            }
            base.internalProcess(query);
        }
    }
}